#!/usr/bin/python3
# @Time    : 2018/6/2 下午 16:39:40  
# @Author  : LaoJI
from . import web
from app.app import basepath
from flask import render_template, jsonify, request, flash, redirect, url_for, current_app
from app.models.base import db
import os
from app.models.Image import ImageFile
from app.forms.image import upForm
import base64
from werkzeug.utils import secure_filename
from PIL import Image
from flask_login import current_user
from app.models.user import User
@web.route('/avatar_sub', methods=['POST'])
def avatar_sub():
    res = {}
    ds = ImageFile.query.all()
    form = upForm()
    uid = None
    user =None
    if not current_user.is_anonymous:
        uid = current_user.get_id()
        user = User.query.get(int(uid))
    if user and request.method == 'POST' and form.validate():
        print(request.files)
        print(request.form)
        file = request.files["avatar_file"]
        fileliu = request.files["avatar_file"].read()
        # print(fileliu)
        # 巨坑！！！
        im =Image.open(file)
        filename = request.files["avatar_file"].filename
        # 保存在本地
        # basepath = os.path.dirname(__file__)  # 当前文件所在路径
        upload_path = os.path.join(basepath, 'statics/Uploads',
                                   secure_filename(filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        im.save(upload_path)
        # 保存在数据库
        image_file = ImageFile(image_name=filename, image=fileliu,uid=uid)

        db.session.add(image_file)

        # flash('修改头像成功')
        user.avatar_url = os.path.join('/statics/Uploads/', filename)
        db.session.add(user)
        db.session.commit()
        res["result"] = os.path.join('/statics/Uploads/', filename)
        return jsonify(res)

    return render_template('up.html', form=form, ds=ds, base64=base64)
